package com.tiger.cloud.util.weChat;

import org.apache.commons.lang3.StringUtils;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;

import static java.lang.System.in;

public class WeChatSignUtil {

    public static void main(String[] args) throws Exception {
        String jsapi_ticket = "jsapi_ticket";

        // 注意 URL 一定要动态获取，不能 hardcode
        String url = "exam.wxcrm.anshipai.com";
        Map<String, String> ret = sign(url);
        for (Map.Entry entry : ret.entrySet()) {
            System.out.println(entry.getKey() + ", " + entry.getValue());
        }
    }

    ;

    public static Map<String, String> sign(String url) throws Exception {
        String str,jsapiTicket;
        String signature = "";
        Map<String, String> result = new HashMap<String, String>(8);
        try {
            jsapiTicket = AccessToken.getTicket();
            if(StringUtils.isEmpty(jsapiTicket)){
                return result;
            }
            String  nonceStr = create_nonce_str();
            String timestamp = create_timestamp();
            //注意这里参数名必须全部小写，且必须有序
            str = "jsapi_ticket=" + jsapiTicket +
                    "&noncestr=" + nonceStr +
                    "&timestamp=" + timestamp +
                    "&url=" + url;
//                        str = "jsapi_ticket=sM4AOVdWfPE4DxkXGEs8VMCPGGVi4C3VM0P37wVUCFvkVAy_90u5h9nbSlYy3-Sl-HhTdfl2fzFy1AOcHKP7qg&noncestr=Wm3WZYTPz0wzccnW" +
//                                "&timestamp=1414587457&url=http://mp.weixin.qq.com?params=value";
            System.out.println(str);
            signature = SHA1(str);
//            MessageDigest crypt = MessageDigest.getInstance("SHA-1");
//            crypt.reset();
//            crypt.update(str.getBytes("UTF-8"));
//            signature = byteToHex(crypt.digest());
            result.put("url", url);
            result.put("jsapi_ticket", jsapiTicket);
            result.put("nonceStr", nonceStr);
            result.put("timestamp", timestamp);
            result.put("signature", signature);
            System.out.println(result.toString());
        } catch (Exception e) {
            throw new Exception("获取签名失败"+e.getMessage().toLowerCase());
        }
        return result;

    }

    private static String byteToHex(final byte[] hash) {
        Formatter formatter = new Formatter();
        for (byte b : hash) {
            formatter.format("%02x", b);
        }
        String result = formatter.toString();
        formatter.close();
        return result;
    }
    public static String SHA1(String decript) {
        try {
            MessageDigest digest = java.security.MessageDigest.getInstance("SHA-1");
            digest.update(decript.getBytes());
            byte messageDigest[] = digest.digest();
            // Create Hex String
            StringBuffer hexString = new StringBuffer();
            // 字节数组转换为 十六进制 数
            for (int i = 0; i < messageDigest.length; i++) {
                String shaHex = Integer.toHexString(messageDigest[i] & 0xFF);
                if (shaHex.length() < 2) {
                    hexString.append(0);
                }
                hexString.append(shaHex);
            }
            return hexString.toString();

        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return "";
    }

    private static String create_nonce_str() {
        return UUID.randomUUID().toString().replace("-","");
    }

    private static String create_timestamp() {
        return Long.toString(System.currentTimeMillis() / 1000);
    }


}
